﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using TXTD.Admin.Framework.CostomException;
using TXTD.Admin.Model.Core;

namespace TXTD.Admin.WebApi.Utilitys.Filters
{
    /// <summary>
    /// 统一异常处理
    /// </summary>
    public class TxtdAdminExceptionFilterAttribute : Attribute, IExceptionFilter
    {
        public ILogger<TxtdAdminExceptionFilterAttribute> _logger;
        public TxtdAdminExceptionFilterAttribute(ILogger<TxtdAdminExceptionFilterAttribute> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 发生异常后
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            //异常处理状态
            if (context.ExceptionHandled == false)
            {
                var controllerName = context.HttpContext.GetRouteValue("controller");
                var actionName = context.HttpContext.GetRouteValue("action");
                var exception = context.Exception;

                ResultModel result = new ResultModel();
                result.Success = false;
                if (exception is BusinessMessageException)
                {
                    result.Message = ((BusinessMessageException)exception).BusinessMessage;
                    context.HttpContext.Response.StatusCode = 200;
                }
                else
                {
                    _logger.LogError(exception, $"控制器{controllerName}的方法{actionName}发生了异常，异常信息为：{exception.Message}");

                    result.Message = "发生异常啦";
                    result.Error = exception.Message;
                    result.ExceptionInfo = Newtonsoft.Json.JsonConvert.SerializeObject(exception);
                    //程序发生异常了  状态改为500
                    context.HttpContext.Response.StatusCode = 500;
                }
                context.Result = new JsonResult(result);

                context.ExceptionHandled = true;
            }
        }
    }
}
